/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.chl.mq._06_properties;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import java.util.Random;

/**
 *
 * @author 陈宏亮
 */
public class DoWoker {

    private final static Random r = new Random();

    public static void main(String[] argv) throws Exception {
        // 创建连接和频道  
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.2.221");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        System.out.println("等待接收");

        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 指定接收者，第二个参数为自动应答，无需手动应答  
        channel.basicConsume("chl_stady", false, consumer);
        channel.basicConsume("chl_work", false, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            if (r.nextBoolean()) {
                System.out.println("拒绝 '" + message + "'");
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println("接收 '" + message + "'");
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }

        }

    }
}
